import * as SecureStore from 'expo-secure-store';

const KEY = 'favorites_v1';

export type FavoriteItem = { id: number; title: string; markedAt: string };

async function read(): Promise<FavoriteItem[]> {
  try {
    const raw = await SecureStore.getItemAsync(KEY);
    if (!raw) return [];
    const data = JSON.parse(raw);
    return Array.isArray(data) ? data : [];
  } catch {
    return [];
  }
}

async function write(items: FavoriteItem[]) {
  try {
    await SecureStore.setItemAsync(KEY, JSON.stringify(items.slice(0, 200)));
  } catch {}
}

export async function getFavorites(): Promise<FavoriteItem[]> {
  return read();
}

export async function isFavorite(id: number): Promise<boolean> {
  const list = await read();
  return list.some((x) => x.id === id);
}

export async function addFavorite(payload: { id: number; title: string }) {
  const now = new Date().toISOString();
  const list = await read();
  const filtered = list.filter((x) => x.id !== payload.id);
  await write([{ id: payload.id, title: payload.title, markedAt: now }, ...filtered]);
}

export async function removeFavorite(id: number) {
  const list = await read();
  await write(list.filter((x) => x.id !== id));
}

